package com.sy.nio.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.sy.nio.c1.ByteBufferUtil.debugAll;

/**
 * @Author yumax
 * @Date 2024 01 04 09 44
 **/
@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        //使用nio来理解阻塞模式
        //1. 创建服务器
        final ServerSocketChannel ssc = ServerSocketChannel.open();
        //2. 绑定监听端口
        ssc.bind(new InetSocketAddress(8989));
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //3. 连接集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            //4. accept 建立与客户端连接，SocketChannel用来与客户端之间通信
            log.debug("connecting...");
            final SocketChannel channel = ssc.accept(); //阻塞方法，线程停止运行
            log.debug("connected ...");
            channels.add(channel);

            for (SocketChannel item : channels) {
                item.read(buffer); //（客户端没有发送数据）会阻塞方法，线程停止，
                buffer.flip();
                debugAll(buffer);
                buffer.clear();
            }

        }

    }
}
